package lew.bing.tom;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class DefaultHtmlHandler implements HtmlHandler{

    private String bashPath;

    public DefaultHtmlHandler() {
        this(null);
    }

    public DefaultHtmlHandler(String bashPath) {
        if (bashPath == null) {
            this.bashPath = "web/webapps/html";
        } else {
            this.bashPath = bashPath;
        }
    }

    @Override
    public void handler(HttpServletRequest request, HttpServletResponse response) {
        // 最好的办法是通过预编译html变成java文件，并将参数代入
        try {
            final String requestURI = request.getRequestURI();
            File file = new File(bashPath, requestURI);
            if (file.exists() && file.isFile() && file.canRead()) {
                response.setContentType("text/html");
                response.setCharacterEncoding("utf-8");
                response.setContentLengthLong(file.length());
                final ServletOutputStream os = response.getOutputStream();
                try(FileInputStream ins = new FileInputStream(file)) {
                    byte[] buffer = new byte[1024];
                    while (ins.read(buffer) != -1) {
                        os.write(buffer);
                        os.flush();
                    }
                }
            }
        } catch (Exception e) {
            log.debug("read file error =>", e);
        }
    }
}
